package org.example.commond.handler.message;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import org.example.commond.AbstractCmdHandler;
import org.example.commond.CommandManager;
import org.example.commond.handler.room.CreatGroupReqHandler;
import org.example.component.UserInfo;
import org.example.config.Im;
import org.example.config.ImConfig;
import org.example.enums.CommandEnum;
import org.example.packets.bean.Group;
import org.example.packets.bean.Message;
import org.example.packets.handler.message.MessageForwardReqBody;
import org.example.packets.handler.room.CreateGroupReqBody;
import org.example.packets.handler.system.RespBody;
import org.example.packets.handler.user.GroupUser;
import org.example.util.JsonUtil;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class MessageForwardReqHandler extends AbstractCmdHandler {

    @Override
    public CommandEnum command() {
        return CommandEnum.COMMAND_FORWARD_MESSAGE_REQ;
    }

    @Override
    public WsResponse handler(Packet packet, ChannelContext channelContext) {

        MessageForwardReqBody reqBody = JsonUtil.format(packet, MessageForwardReqBody.class);

        ChatReqHandler chatReqHandler = CommandManager.getCommand(CommandEnum.COMMAND_CHAT_REQ, ChatReqHandler.class);

        // 创建要转发的消息列表。 准备完成
        List<Message> messages = reqBody.getMessages().stream().sorted(Comparator.comparing(Message::getSendTime)).map(x -> {
            Message message = new Message();
            message.setContent(x.getContent());
            message.setSenderId(UserInfo.id());
            message.setFiles(x.getFiles());
            return message;
        }).collect(Collectors.toList());

        // 给这些chat发消息，不需要确认。
        for (String chat : reqBody.getChats()) {
            for (Message message : messages) {
                message.setId(IdUtil.getSnowflake().nextIdStr());
                message.setRoomId(chat);
                WsRequest wsRequest = WsRequest.fromText(JSONObject.toJSONString(message), ImConfig.CHARSET);
                chatReqHandler.handler(wsRequest, channelContext);
            }
        }

        // 开始整理创建, 发过来的用户列表中可能存在已经创建的会话， 这种情况下不需要重新创建，
        CreatGroupReqHandler command = (CreatGroupReqHandler) CommandManager.getCommand(CommandEnum.COMMAND_CREATE_GROUP_REQ);
        for (String user : reqBody.getUsers()) {
            Group group = UserInfo.friend(user);
            if (group != null) {
                if (reqBody.getChats().contains(group.getRoomId())) {
                    continue;
                }
            } else {
                CreateGroupReqBody createGroupReqBody = new CreateGroupReqBody();
                createGroupReqBody.setIsFriend(true);
                createGroupReqBody.setRoomName("");
                createGroupReqBody.setUsers(List.of(new GroupUser().setId(user)));
                WsRequest wsRequest = WsRequest.fromText(JSONObject.toJSONString(createGroupReqBody), ImConfig.CHARSET);
                command.handler(wsRequest, channelContext);

                group = UserInfo.friend(user);
            }
            Assert.notNull(group);
            assert group != null;
            for (Message message : messages) {
                message.setId(IdUtil.getSnowflake().nextIdStr());
                message.setRoomId(group.getRoomId());
                WsRequest wsRequest = WsRequest.fromText(JSONObject.toJSONString(message), ImConfig.CHARSET);
                chatReqHandler.handler(wsRequest, channelContext);
            }
        }

        WsResponse wsResponse = WsResponse.fromText(RespBody.success(CommandEnum.COMMAND_FORWARD_MESSAGE_RESP), Im.CHARSET);
        Im.send(channelContext, wsResponse);

        return null;
    }
}
